<?php
namespace app\controller;

use app\BaseController;
use think\Controller;
use think\Facade\Db;
use think\captcha\facade\Captcha;
use think\facade\Session;
class Api extends BaseController
{

    public static function checkIsLogin(){
        if(Session::has('login')){
            if(Session::get('login') != 1){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }
    public static function getUser(){
        if(Session::has('user')){
            return Session::get('user');
        }else{
            return null;
        }
    }
    public static function updateUser(){
        if(Session::has('user')){
            $user = Session::get('user');
            $user = Db::table('user')->where('id', $user['id'])->find();
            Session::set('user', $user);
        }
    }

    /***
     * 查找推荐人
     * @param $inviteCode
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkInviteCode($inviteCode)
    {
        if(empty($inviteCode)){
            return show(500,"邀请码不能为空", null);
        }
        $res =  Db::table('user')->where('id', $inviteCode)->find();
        if($res!=null){
            return show(200,"校验通过", null);
        }else{
            return show(500,"邀请码错误", null);
        }
    }

    /***
     * 判断姓名
     * @param $nick
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkNick($nick)
    {
        if(empty($nick)){
            return show(500,"姓名不能为空", null);
        }
        $res =  Db::table('user')->where('name', $nick)->select()->toArray();
        if($res!=null){
            return show(500,"已存在该用户，请重新设置", null);
        }else{
            return show(200,"校验通过", null);
        }
    }

    public function checkTel($tel)
    {
        if(empty($tel)){
            return show(500,"手机号不能为空", null);
        }
        $res =  Db::table('user')->where('phone', $tel)->select()->toArray();
        if($res!=null){
            return show(500,"已存在该手机号，请重新设置", null);
        }else{
            return show(200,"校验通过", null);
        }
    }


    public function checkCode($code)
    {
        if( !Captcha::check($code))
        {
            return show(500,"验证失败", null);
        }else{
            return show(200,"校验通过", null);
        }
    }

    public function ApiReg($inviteCode,$nick,$tel,$pwd,$payPwd)
    {
        if(empty($inviteCode)||empty($nick)||empty($tel)||empty($pwd)||empty($payPwd)){
            return show(500,"请检查输入信息是否有空", null);
        }
        $data = ['name' => $nick,
            'head' => 'static/Theme/images/member.png',
            'phone' => $tel,
            'pwd' => $pwd,
            'pay_pwd' => $payPwd,
            'is_pay_pwd' => 1,
            'is_phone' => 1,
            'is_up' => 1,
            'is_down' => 0,
            'level' => 0,];
        $userId = Db::name('user')->insertGetId($data);
        if($userId!=null){
            $user = Db::table('user')->where('id', $userId)->find();
            Session::set('login', 1);
            Session::set('user', $user);
            return show(200,"注册成功", "home");
        }else{
            return show(500,"注册失败，请稍后再试！", null);
        }
    }

    public function ApiLogin($tel,$pwd,$code)
    {
        if( !Captcha::check($code))
        {
            return show(500,"验证码失效", null);
        }else{
            $user = Db::table('user')->where('phone', $tel)->find();
            if($user!=null){
                if($user['pwd'] === $pwd){
                    Session::set('login', 1);
                    Session::set('user', $user);
                    return show(200,"登录成功", "home");
                }else{
                    return show(500,"密码错误！", null);
                }
            }else{
                return show(500,"账号不存在！", null);
            }
        }
    }

    public function editNick($nick)
    {
        if(!$this->checkIsLogin()){
            return show(100,"已掉线，请重新登录", null);
        }
        if(empty($nick)){
            return show(500,"姓名不能为空", null);
        }
        $user = $this->getUser();
        if($user['name'] === $nick){
            return show(200,"设置成功", null);
        }
        $res =  Db::table('user')->where('name', $nick)->select()->toArray();
        if($res!=null){
            return show(500,"已存在该名称，请重新设置", null);
        }else{
            $user = $this->getUser();
            if($user!=null){
                Db::name('user')->where('id', $user['id'])->update(['name' => $nick]);
                $this->updateUser();
                return show(200,"设置成功", "Setting");
            }
        }
    }
    public function editPwd($ow,$nw)
    {
        if(!$this->checkIsLogin()){
            return show(100,"已掉线，请重新登录", null);
        }
        if(empty($ow)||empty($nw)){
            return show(500,"旧密码或新密码不能为空", null);
        }
        $user = $this->getUser();
        if($user['pwd'] === $ow){
            Db::name('user')->where('id', $user['id'])->update(['pwd' => $nw]);
            Session::clear();
            return show(200,"设置成功，请重新登录", "login");
        }else{
            return show(500,"设置失败，旧密码错误！", null);
        }
    }

    public function editPayPwd($ow,$nw)
    {
        if(!$this->checkIsLogin()){
            return show(100,"已掉线，请重新登录", null);
        }
        if(empty($ow)||empty($nw)){
            return show(500,"旧支付密码或新支付密码不能为空", null);
        }
        $user = $this->getUser();
        if($user['pay_pwd'] === $ow){
            Db::name('user')->where('id', $user['id'])->update(['pay_pwd' => $nw]);
            $this->updateUser();
            return show(200,"设置成功", "Setting");
        }else{
            return show(500,"设置失败，旧支付密码错误！", null);
        }
    }



    public function wxcash($openId,$money)
    {
        $pub = config('weixin');
        $appid = $pub['appid'];//商户账号appid
        $mch_id = $pub['mch_id'];//商户号
        $key = $pub['key'];
        $openid = $openId;//授权用户openid

        $arr = array();
        $arr['mch_appid'] = $appid;
        $arr['mchid'] = $mch_id;
        $arr['nonce_str'] = md5(uniqid(microtime(true),true));//随机字符串，不长于32位
        $arr['partner_trade_no'] = '123456789' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);//商户订单号
        $arr['openid'] = $openid;
        $arr['check_name'] = 'NO_CHECK';//是否验证用户真实姓名，这里不验证
        $arr['amount'] = $money * 100;//付款金额，单位为分
        $arr['desc'] = "零钱提现";//描述信息
        $arr['spbill_create_ip'] = '192.168.0.1';//获取服务器的ip
        //封装的关于签名的算法
        $arr['sign'] = $this->makeSign($arr,$key);//签名
        $var = $this->arrayToXml($arr);
        // dump($arr['sign'] );exit;
        $xml = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',$var,30);
        libxml_disable_entity_loader(true);
        $rdata = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
        //eblog('cash_xmldata',$rdata);
         dump($rdata);exit;
        $return_code = trim(strtoupper($rdata['return_code']));
        $result_code = trim(strtoupper($rdata['result_code']));
        if ($return_code == 'SUCCESS' && $result_code == 'SUCCESS') {
            $isrr = array(
                'status'=>1,
                'msg' => '',
            );
        } else {
            $err_code_des = $rdata['err_code_des'];
            $isrr = array(
                'status' => 0,
                'msg' => $err_code_des,
            );
        }
        return $isrr;
    }

    protected function makesign($data,$key)
    {
        //获取微信支付秘钥
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp = $string_a."&key=".$key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        // $result = strtoupper(hash_hmac("sha256",$string_sign_temp,$key));
        return $result;
    }

    protected function arraytoxml($data){
        $str='<xml>';
        foreach($data as $k=>$v) {
            $str.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $str.='</xml>';
        return $str;
    }

    protected function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
    {
        $pub = config('weixin');
        $ch = curl_init();//初始化curl
        dump($pub['api_cert']);
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
        curl_setopt($ch, CURLOPT_SSLCERT, $pub['api_cert']);//证书位置
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
        curl_setopt($ch, CURLOPT_SSLKEY, $pub['api_key']);//证书位置
        curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
        curl_setopt($ch, CURLOPT_CAINFO, $pub['api_key']);
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);//全部数据使用HTTP协议中的"POST"操作来发送
        $data = curl_exec($ch);//执行回话
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }


}
